//
//  CZPlaceholderTextView.swift
//  GZWeibo666
//
//  Created by ksl on 15/12/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

//自定义 textView,里面有一个占位文本,当没有内容的时候会显示出来
class CZPlaceholderTextView: UITextView {
    
    //提供属性,让外界来设置占位文本
    var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
            placeholderLabel.font = font
        }
    }
    
    //构造方法    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"textDidChange", name:UITextViewTextDidChangeNotification, object: self)
    }

    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //实现通知方法
    func textDidChange() {
        //没有内容时,显示占位文本,有文本则隐藏
        placeholderLabel.hidden = hasText()
    }
    
    //MARK: - 懒加载
    ///占位文本,如果提供 label 给外界访问,可能会被非法操作
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        self.addSubview(label)
        
        //添加约束,独立的 view,
        label.translatesAutoresizingMaskIntoConstraints = false
        //顶部约束
        self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
        //水平约束
        self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
        
        label.sizeToFit()
        
        return label
    }()
}
